﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Windows.UI.Xaml;
using CeskyRozhlasRT.DataModel;
using CeskyRozhlasRT.Parsing;
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace Win81App.DataModel
{

    public class WebDataSource
    {
        public static String UiConfigPath { get; set; }

        private WebDataSource()
        {
            UiConfigPath = "ms-appx:///Assets/UIConfig.xml";
        }

        private static readonly WebDataSource MyWebData = new WebDataSource();
        private static readonly WebContentDescription _webContentDescription = new WebContentDescription();

        // ReSharper disable MemberCanBePrivate.Global

        public WebContentDescription WebContentDescription
        {
            get { return _webContentDescription; }
        }

        // ReSharper restore MemberCanBePrivate.Global

        public static async Task<IEnumerable<StationsGroup>> GetGroupsAsync()
        {
            await MyWebData.GetSampleDataAsync(UiConfigPath);
            return _webContentDescription.Groups;
        }

        public static async Task<StationsGroup> GetGroupAsync(string uniqueId)
        {
            await MyWebData.GetSampleDataAsync(UiConfigPath);
            // Simple linear search is acceptable for small data sets
            var matches = _webContentDescription.Groups.Where(group => group.UniqueId.Equals(uniqueId));
            return matches.FirstOrDefault();
        }

        public static async Task<StationInfo> GetItemAsync(string uniqueId)
        {
            await MyWebData.GetSampleDataAsync(UiConfigPath);
            var matches = _webContentDescription.Groups.SelectMany(group => group.Items).Where(item => item.WebUid.Equals(uniqueId));
            return matches.FirstOrDefault();
        }

        // ReSharper disable MemberCanBePrivate.Global
        public async Task GetSampleDataAsync(String iConfigFileName)
        {
            GroupConfigParser.SyncContext = SynchronizationContext.Current;

            if (_webContentDescription.Groups.Count > 0)
            {
                return;
            }
            GroupConfigParser.ParseGroupConfigAsync(await GetConfigXmlReader(iConfigFileName), _webContentDescription);
        }

        private static async Task<XmlReader> GetConfigXmlReader(string iConfigFileName)
        {
            var aConfigFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(iConfigFileName));
            var aXmlReader = XmlReader.Create((await aConfigFile.OpenReadAsync()).AsStreamForRead());
            return aXmlReader;
        }

        // ReSharper restore MemberCanBePrivate.Global
    }
}
